<template>
	<view>
		<!-- 海报 -->
		<!-- 海报生成器 -->
		<piaoyi-poster ref="piaoyiPostor" @temp-file-path="tempFilePath" :img-image="img" :shop-name="QrVideos.name"
			:title="title" :detail="detail" :price="price" :imgImage="QrVideos.imageUrl" yurts="中国" :qrImage="qrImage"
			years="2025" :tags1="QrVideos.tagsName" />

		<!-- 小程序码生成器 -->
		<QrCodeGenerator ref="CodeGenerator" page="pages/of_play/play/play" :scene="{ id: videoId, userId: user.id }"
			:autoColor="true" :color="{ r: 0, g: 0, b: 0 }" envVersion="release" @success="onQrCodeSuccess"
			@error="onQrCodeError" @loading="onLoading" />

		<!-- 展示生成后的海报图 v-if="posterIf"-->
		<view class="poster-img" @touchmove.stop v-if="posterIf">
			<view class="poster-icon">
				<navigator url="/pages/geid/coins/coins">
					<uni-icons type="help" size="30" color="#ff0000"></uni-icons>
				</navigator>
				<view>

				</view>

				<view @click.stop="posterClose">
					<uni-icons type="close" size="30" color="#ff0000"></uni-icons>
				</view>
			</view>
			<!-- :src="img" -->
			<view style="width: 80%;height: 55%;">
				<image :src="img" style="width: 100%;height: 100%;" show-menu-by-longpress></image>
			</view>
			<!-- 导航 -->
			<view class="share">
				<view @click.stop="shareImgFunction">保存</view>
			</view>

		</view>

	</view>

	<view class="social-actions">
		<!-- 右下角操作按钮 -->
		<view class="action-buttons">
			<view class="action-item" @click.stop="toggleLike">
				<image :src="liked ? likeActiveIcon : likeIcon" mode="aspectFit" />
				<text>{{ likeCount }}</text>
			</view>
			<view class="action-item" @click.stop="showCommentPanel">
				<image :src="commentIcon" mode="aspectFit" />
				<text>{{commentsTotal}}</text>
			</view>
			<view class="action-item" @click.stop="openImg">
				<image :src="shareIcon" mode="aspectFit" />
				<text>分享</text>
			</view>
			<view v-if="episode" class="action-item" @click.stop="showEpisodesPanel">
				<image :src="episodesIcon" mode="aspectFit" />
				<text>选集</text>
			</view>
		</view>


		<!-- 评论面板 -->
		<view v-if="isMianban" @click.stop :class="['comment-panel', { 'show': isCommentVisible }]"
			:style="{ transform: isCommentVisible ? 'translateY(0)' : 'translateY(100%)' }">
			<view class="panel-header">
				<text>评论</text>
				<image :src="closeIcon" @click.stop="hideCommentPanel" mode="aspectFit" />
			</view>

			<!-- 滚动内容区 -->
			<scroll-view scroll-y class="comment-list" @touchmove.stop @scrolltolower="Commentscroll">
				<view v-for="(comment, index) in comments" :key="index" class="comment-item">
					<!-- 用户信息 -->
					<view class="comment-header">
						<image class="avatar" :src="comment.userImg" mode="aspectFill" />
						<view class="user-info">
							<text class="username">{{ comment.username }}</text>
							<text class="time">{{ comment.time }}</text>
						</view>
					</view>

					<!-- 评论内容 -->
					<view class="comment-content">
						<text>{{ comment.content }}</text>
					</view>
				</view>
			</scroll-view>

			<!-- 固定输入框 -->
			<view class="comment-input">
				<input @click.stop v-model="newComment" placeholder="写下你的评论..." @confirm="submitComment"
					:adjust-position="true" :auto-focus="isCommentVisible" class="input-box" />
				<button style="background: #ff0000; border-radius: 20rpx; color: #fff;" size="mini"
					@click.stop="submitComment">发送</button>
			</view>
		</view>

		<!-- 选集面板 -->
		<view v-if="isMianban" @click.stop :class="['episodes-panel', { 'show': isEpisodesVisible }]"
			:style="{ transform: isEpisodesVisible ? 'translateY(0)' : 'translateY(100%)' }">
			<!-- 骨架屏 -->
			<view>
				<SkeletonScreen v-if="loadings" PercentagePostion="static" :heightPercentage="'60vh'"></SkeletonScreen>
			</view>
			<view class="panel-header">
				<text>选集</text>
				<image :src="closeIcon" @click.stop="hideEpisodesPanel" mode="aspectFit" />
			</view>
			<scroll-view scroll-y class="episodes-list" @touchmove.stop>
				<view class="episodes-grid">
					<view v-for="(episode, index) in episodes" :key="index" class="episode-item"
						:class="{ 'active': episode.id === currentEpisodeId && episode.id === PlayId}"
						@click.stop="selectEpisode(episode)">
						<view class="episodes-vip" v-if="episode.status == 2">VIP</view>
						<text>{{ episode.videoJi }}</text>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 背景遮罩 -->
		<view v-if="isCommentVisible || isEpisodesVisible" class="mask" @click.stop="hideAllPanels"></view>
	</view>

</template>

<script setup>
	import {
		ref,
		computed,
		watch
	} from 'vue';
	import {
		playComments,
		insertCommend,
		PlayVideosUrl,
		watchDelete
	} from '@/API/ofPlayApis.js';

	const prop = defineProps({
		videoContent: {
			type: Object,
			default: {}
		},
		episode: {
			type: Boolean,
			default: false
		},
		imgUrl: {
			type: String,
			default: ''
		}

	})

	const PlayId = computed(() => prop.videoContent.id);
	const videoId = computed(() => prop.videoContent.videoId);
	const likeCount = computed(() => prop.videoContent.collects);
	const liked = computed(() => prop.videoContent.ifCollect);
	const episodesCount = computed(() => prop.videoContent.videoJi);
	const QrVideos = computed(() => prop.videoContent.collectionPlays[0]);

	// const likeCou = ref(prop.videoContent);
	console.log("prop.videoContent:", prop.videoContent)
	console.log("videoId:", videoId.value)
	console.log("PlayId:", PlayId.value)
	console.log("prop.videoContentImurl:", prop.videoContent.collectionPlays[0])

	// 先获取用户信息然后进行存储
	// #ifdef MP-WEIXIN
	const user = ref(uni.getStorageSync("user"));
	// #endif

	// 弹出分享图片形成函数列表
	import piaoyiPoster from '@/components/piaoyi-poster/piaoyi-poster.vue'
	import QrCodeGenerator from '@/components/piaoyi-poster/QrCodeGenerator.vue'
	// ========== 组件引用 ==========
	const piaoyiPostor = ref(); //绘制ref
	const CodeGenerator = ref() //形成小程序码ref
	// ========== 响应式数据 ==========
	const img = ref(null)
	const title = ref('ikran 影视厅')
	const detail = ref('超蓝光，无删减，最新精彩影片')
	const price = ref(95)
	const shopName = ref('我的好母亲')
	const qrImage = ref();
	const posterIf = ref(false)
	const loadings = ref(false)

	// 图标资源
	const likeIcon = '/static/coin_icon/xin.png';
	const likeActiveIcon = '/static/coin_icon/xin-s.png';
	const commentIcon = '/static/coin_icon/commend.png';
	const shareIcon = '/static/coin_icon/share.png';
	const episodesIcon = '/static/coin_icon/ji.png';
	const closeIcon = '/static/coin_icon/exit.png';

	// 点赞状态
	const pageNum = ref(1);

	// 选集面板
	const isEpisodesVisible = ref(false);
	const episodes = ref([]);
	const isMianban = ref(false)

	// 评论面板
	const isCommentVisible = ref(false);
	const comments = ref([]); //评论内容
	const newComment = ref(''); // 新添加的评论
	const commentsTotal = ref();

	// 获取评论
	const CommentsFunction = async (pege, videoId) => {
		isMianban.value = true
		let res = await playComments(pege, videoId);
		console.log("评论：", res.list);
		comments.value = comments.value.concat(res.list);
		pageNum.value = res.nextPage;
		commentsTotal.value = res.total;
		for (let i = 0; i < comments.value.length; i++) {
			comments.value[i].time = formatTimestamp(comments.value[i].time);
		}
	}

	// 获取videoId关联的所有的Url
	const PlayVideosUrlFunction = async (videoIds) => {
		console.log("episodes.value:", episodes.value.length)
		if (episodes.value == 0) {
			// #ifdef MP-WEIXIN
			let user = uni.getStorageSync("user");
			let userId = user.id;
			// #endif
			let res = await PlayVideosUrl(userId, videoIds);
			console.log("所有的Url：", res.list);
			episodes.value = res.list;
			loadings.value = false
		}
		loadings.value = false
	}

	// 显示评论面板
	function showCommentPanel() {
		isCommentVisible.value = true;
	}

	// 隐藏评论面板
	function hideCommentPanel() {
		isCommentVisible.value = false;
	}

	// 显示选集面板
	function showEpisodesPanel() {
		loadings.value = true;
		isEpisodesVisible.value = true;
		console.log("点击率")
		currentEpisodeId.value = PlayId.value;
		PlayVideosUrlFunction(videoId.value);
	}

	// 隐藏选集面板
	function hideEpisodesPanel() {
		isEpisodesVisible.value = false;
	}

	// 隐藏所有面板
	function hideAllPanels() {
		hideCommentPanel();
		hideEpisodesPanel();
	}

	// 点击选集项
	const currentEpisodeId = ref(1);
	const currentPage = ref(1);

	const emit = defineEmits(['select-episode']);
	// 点击选集项
	function selectEpisode(episode) {
		// 触发事件，通知母页播放该集数
		emit('select-episode', episode);
		currentEpisodeId.value = episode.id;
		uni.showToast({
			title: `正在播放第${episode.videoJi}集`
		});
		hideEpisodesPanel();
	}


	// 点赞切换
	function toggleLike() {
		// 先获取用户信息然后进行存储
		// #ifdef MP-WEIXIN
		let user = uni.getStorageSync("user");
		let userId = user.id;
		// #endif

		if (liked.value) {
			prop.videoContent.collects--;
			let url = "/collectionPlayCllect/delete"
			watchDeleteFunction(url, userId, PlayId.value, videoId.value, episodesCount.value)
		} else {
			prop.videoContent.collects++;
			let url = "/collectionPlayCllect/insert"
			watchDeleteFunction(url, userId, PlayId.value, videoId.value, episodesCount.value)
		}
		prop.videoContent.ifCollect = !prop.videoContent.ifCollect;
	}
	// 插入和删除点赞记录
	const watchDeleteFunction = async (url, userId, urlId, videoId, episodesCount) => {
		let res = await watchDelete(url, userId, urlId, videoId, episodesCount);
		console.log("进行点赞插入-删除：", res);
	}


	// 评论插入
	function submitComment() {
		if (newComment.value.trim() === '') {
			uni.showToast({
				title: '空字符不能发送！',
				icon: 'none'
			})
			return;
		}

		// 先获取用户信息然后进行存储
		// #ifdef MP-WEIXIN
		let user = uni.getStorageSync("user");
		let username = user.username;
		let userId = user.id;
		let userImg = user.userImg;
		// #endif

		inserFunction(videoId.value, username, userId, newComment.value, userImg);
		// inserFunction(1, 'norali', 183, 'wwwwwwww', 'oooo');
	}
	// 评论插入
	const inserFunction = async (videoId, username, userId, content, userImg) => {
		let res = await insertCommend(videoId, username, userId, content, userImg);
		res.time = formatTimestamp(res.time);
		if (res) {
			comments.value.unshift(res);
			//   console.log("最后");
			newComment.value = '';
		}
		console.log("新插入的评论：", res);
		console.log("新评论数组：", comments.value);
	}
	CommentsFunction(pageNum.value, videoId.value)

	// 集数触底刷新
	function Commentscroll() {
		if (pageNum.value > 1) {
			CommentsFunction(pageNum.value, videoId.value)
			console.log("评论触底了")
		}
	}
	//实时更新评论信息和观看记录
	watch(
		() => videoId.value,
		(newId) => {
			if (newId) {
				console.log("newVideoId:", newId)
				comments.value = [];
				CommentsFunction(1, newId);

			}
		}
		//, {
		// 	immediate: true
		// }
	);
	// 时间码转换
	function formatTimestamp(timestamp) {
		const date = new Date(timestamp);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
		const day = String(date.getDate()).padStart(2, '0');
		const hour = String(date.getHours()).padStart(2, '0');
		const minute = String(date.getMinutes()).padStart(2, '0');

		return `${year}/${month}/${day} ${hour}:${minute}`;
	}


	// 转发逻辑
	// ========== 方法定义 ==========
	const openImg = async () => {
		console.log("我会自动执行的代码！")
		uni.showLoading({
			title: "正在生成中..."
		})
		console.log("小程序码触发")
		CodeGenerator.value?.fetchQrCode()
			.then((qrCodePath) => {
				// 二维码生成成功
				console.log("二维码生成成功，路径:", qrCodePath);
				uni.hideLoading()

				// 打开海报
				piaoyiPostor.value?.open();
				posterIf.value = true;
			})
			.catch((error) => {
				// 二维码生成失败
				console.error("生成二维码失败:", error);
				uni.showToast({
					title: '生成失败',
					icon: 'none'
				});
			});

	}

	function tempFilePath(filePath) {
		console.log("海报地址：", filePath);
		img.value = filePath
	}

	function posterClose() {
		posterIf.value = false;
		uni.hideLoading();
	}
	// 小程序码返回的临时地址
	const onQrCodeSuccess = (filePath) => {
		console.log('小程序码生成成功:', filePath)
		qrImage.value = filePath

	}
	// 海报处理函数
	function shareImgFunction(index) {
		let imgPath = img.value;
		console.log("海报临时地址：", imgPath);
		saveImageToPhotos(imgPath);
	}
	// 将临时图片保存到手机相册
	const saveImageToPhotos = async (tempFilePath) => {
		uni.showLoading({
			title: "处理中..."
		})
		try {
			// 将临时文件保存到本地相册
			await uni.saveImageToPhotosAlbum({
				filePath: tempFilePath
			});
			uni.hideLoading();
			uni.showToast({
				title: '保存成功',
				icon: 'success'
			});
		} catch (err) {
			uni.showToast({
				title: '保存失败',
				icon: 'error'
			});
			console.error('保存图片失败：', err);
		}
	};
</script>

<style lang="scss">
	.social-actions {
		position: fixed;
		right: 30rpx;
		bottom: 200rpx;
		z-index: 999;

		.action-buttons {
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 40rpx;
		}

		.action-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			color: #fff;

			image {
				width: 60rpx;
				height: 60rpx;
				margin-bottom: 8rpx;
			}

			text {
				font-size: 22rpx;
			}
		}


		.comment-panel,
		.episodes-panel {
			position: fixed;
			left: 0;
			bottom: 0;
			width: 100%;
			height: 60vh; // 占屏幕高度的60%
			background-color: #fff;
			border-top-left-radius: 20rpx;
			border-top-right-radius: 20rpx;
			box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.1);
			overflow: hidden;
			transition: transform 0.3s ease;
			z-index: 1000;
			display: flex;
			flex-direction: column;

			.panel-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 30rpx;
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				border-bottom: 1rpx solid #eee;

				image {
					width: 40rpx;
					height: 40rpx;
				}
			}

			.comment-list,
			.episodes-list {
				flex: 1;
				padding: 20rpx;
				overflow-y: auto;

				.comment-item {
					margin-bottom: 30rpx;
					background-color: #fff;
					border-radius: 16rpx;
					padding: 24rpx;
					box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
					padding-right: 30rpx;

					.comment-header {
						display: flex;
						align-items: center;
						margin-bottom: 20rpx;

						.avatar {
							width: 70rpx;
							height: 70rpx;
							border-radius: 50%;
							margin-right: 20rpx;
						}

						.user-info {
							display: flex;
							flex-direction: column;

							.username {
								font-size: 28rpx;
								color: #333;
								font-weight: bold;
							}

							.time {
								font-size: 22rpx;
								color: #999;
								margin-top: 6rpx;
							}
						}
					}

					.comment-content {
						font-size: 28rpx;
						color: #555;
						line-height: 1.6;
					}
				}

				.episodes-grid {
					width: 100%;
					display: grid;
					grid-template-columns: repeat(7, 1fr);
					gap: 15rpx;
					padding: 0 40rpx 0 0; // 左右内边距都设置为 30rpx
					box-sizing: border-box; // 确保内边距包含在总宽度内
				}

				.episode-item {
					aspect-ratio: 1 / 1;
					background-color: #e8e8e8;
					color: #000;
					font-weight: bold;
					font-size: 24rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					border-radius: 15rpx;

					&.active {
						background-color: #ff0000; // 高亮颜色
						color: #fff;
						font-weight: bold;
					}
				}

				.episodes-vip {
					position: absolute;
					color: #f6f6f6;
					top: 0;
					background-color: #ff0000;
					font-size: 18rpx;
					padding: 2rpx 20rpx;
					border-bottom-left-radius: 15rpx;
					border-bottom-right-radius: 15rpx;

				}
			}

			.comment-input {
				display: flex;
				align-items: center;
				padding: 20rpx;
				border-top: 1rpx solid #eee;
				background-color: #f9f9f9;

				.input-box {
					flex: 1;
					height: 70rpx;
					padding: 0 20rpx;
					font-size: 26rpx;
					border: 1rpx solid #ddd;
					border-radius: 30rpx;
					margin-right: 20rpx;
					color: #333;
				}
			}
		}



		.mask {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: transparent;
			backdrop-filter: blur(2px);
			z-index: 998;
		}
	}

	.mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: transparent;
		backdrop-filter: blur(2px);
		z-index: 998;
	}

	.poster-img {
		width: 100%;
		height: 100vh;
		position: fixed;
		z-index: 1000;
		top: 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: rgba(0, 0, 0, 0.8);
		overflow: hidden;

		.poster-icon {
			width: 100%;
			display: flex;
			position: relative;
			box-sizing: border-box;
			padding: 20rpx 50rpx;
			align-items: center;
			justify-content: space-between;
		}

		.share {
			position: relative;
			z-index: 1000;
			margin-top: 40rpx;
			border-radius: 20rpx;
			background-color: #ff0000;
			padding: 20rpx 100rpx;
		}
	}
</style>